package com.guanyong.admin.handle;


import com.guanyong.utils.Cache.ICahce.ICache;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.LogHelper.LogHelper;
import com.guanyong.utils.NetUtils.CookieUtils;
import com.guanyong.utils.UniqueID.LoginTokenID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by Eric.Zhang on 2017/3/31.
 */
@Service
public class TokenHelper {
    @Autowired
    ICache cache;

    @Value("${mortise.usercas.multilogin}")
    String mortisecasmultiLogin;
    @Value("${mortise.usercas.LoginToken}")
    String mortisecasLoginToken;
    @Value("${mortise.usercas.cookie.loginToken}")
    String mortiseloginToken;
    @Value("${mortise.usercas.cookie.domain}")
    String mortiseloginDomain;

    /**
     * 设置令牌
     * @param uid
     * @param pwd
     * @param reponse
     * @param request
     */
    public void setCasToken( String uid,
                             String pwd,
                             HttpServletResponse reponse, HttpServletRequest request) {
        LoginTokenID ltID = new LoginTokenID(uid, pwd);
        if (ltID != null) {
            String ltcookie = ltID.toString();
            if (ltcookie == null || ltcookie.equals("")) {
                LogHelper.logger().error(uid + "生成令牌失败2！");
            } else {
                String token = ltID.getUniqueObjectID().toString();
                if (mortisecasmultiLogin.equals("true")) {
                    HashSet<String> list = (HashSet<String>) cache.get(mortisecasLoginToken, uid);
                    if (list == null) {
                        list = new HashSet<String>();
                    }
                    if (!list.contains(token)) {
                        list.add(token);
                        cache.put(mortisecasLoginToken, uid, list);
                    }
                } else {
                    //用户的登录唯一标示写入全局缓存，用作一个用户只能登录一次
                    cache.put(mortisecasLoginToken, uid, token);
                }
                CookieUtils.addCookie(reponse, mortiseloginToken,ltID.toString(),0,mortiseloginDomain,"/");
            }
        } else {
            LogHelper.logger().error(uid + "生成令牌失败1！");
        }

    }

    /**
     * 验证令牌
     *
     * @param uid
     * @param token
     * @return 1 验证成功 0 令牌不存在 -1 验证失败
     */
    public Integer exsitToken(String uid, String token) {
        if (mortisecasmultiLogin.equals("true")) {
            HashSet<String> list = (HashSet<String>) cache.get(mortisecasLoginToken, uid);
            if (list == null) {
                return 0;
            } else {
                if (list.contains(token)) {
                    return 1;
                } else {
                    return 0;
                }
            }
        } else {
            //用户的登录唯一标示写入全局缓存，用作一个用户只能登录一次
            Object tk = cache.get(mortisecasLoginToken, uid);
            if (tk == null) {
                return 0;
            } else {
                if(String.valueOf(tk).equals(token)){
                    return 1;
                }else{
                    return -1;
                }
            }
        }
    }

    /**
     * 获取令牌
     * @param request
     * @return
     */
    public ResultObject<LoginTokenID> getToken(HttpServletRequest request){
        Cookie cookie = CookieUtils.getCookieByName(request,mortiseloginToken);
        String sign =cookie==null?"":cookie.getValue();
        ResultObject<LoginTokenID> resultObject =new ResultObject<LoginTokenID>();
        if (sign != "") {
            try {
                LoginTokenID ltID = new LoginTokenID(sign);
                resultObject.setResult(ltID);
            } catch (Exception ex) {
                resultObject.setCode(ResultCode.NoLogin);
            }
        }else{
            resultObject.setCode(ResultCode.NoLogin);
        }
        return resultObject;
    }

    /**
     * 删除令牌
     * @param request
     */
    public void delMyCasToken(HttpServletRequest request,HttpServletResponse response){
        CookieUtils.delCookie(request,response,mortiseloginToken);
    }
}